package com.msmall.community.mood.service.impl;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.msmall.base.pager.PaginationSupport;
import com.msmall.base.service.impl.BaseManagerImpl;
import com.msmall.base.util.ConstantDB;
import com.msmall.community.mood.dao.MoodDao;
import com.msmall.community.mood.model.Mood;
import com.msmall.community.mood.service.MoodManager;
import com.msmall.community.user.service.UserManager;

public class MoodManagerImpl extends BaseManagerImpl<Mood, Long> implements MoodManager{
	
	private static final Log log = LogFactory.getLog(MoodManagerImpl.class);
	
	private MoodDao moodDao;

	private UserManager userManager;
	
	public void setMoodDao(MoodDao moodDao) {
		this.moodDao = moodDao;
	}
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
	/**
	 * 获得用户当前的心情，最新的一条记录
	 * @param userid
	 * @return
	 * @throws Exception 
	 */
	public Mood getMoodByUserid(Long userid) throws Exception {
		try{
			PaginationSupport page = new PaginationSupport();
			page.setPageIndex(1);
			page.setPageSize(1);
			getPagination(page, userid);
			if(page.getItems() != null && page.getItems().size() >0)
				return (Mood) page.getItems().get(0);
			return null;
		}catch(Exception e){
			log.error(e);
			throw e;
		}
	}
	/**
	 * 获得用户所有的心情
	 * @param userid
	 * @return
	 * @throws Exception 
	 */
	public void getPagination(PaginationSupport page, Long userid) throws Exception {
		try{
			String queryString = "From Mood m where m.userid="+userid + " order by m.moodId DESC";
			page.setQueryString(queryString);
			getPagination(page);
		}catch(Exception e){
			log.error(e);
			throw e;
		}
	}
	/**
	 * 获得用户好友的心情列表。用来在本人空间首页显示
	 */
	public void getFriendMood(PaginationSupport page, Long userid) throws Exception{
		try{
			String queryString = " select m From Mood m, Roster r, RosterGroup rg WHERE rg.userid=" + userid
					+ " AND r.group.groupid=rg.groupid AND m.userid=r.userid order by m.moodId DESC";
			page.setQueryString(queryString);
			getPagination(page);
		}catch(Exception e){
			log.error(e);
			throw e;
		}
	}
	public void saveMood(Mood mood, Long userid) throws Exception {
		try{
			mood.setCreateTime(new Date());
			mood.setVisible(ConstantDB.VISIBLE);
			mood.setUserid(userid);
			mood.setDownAmount(0);
			mood.setForwardAmount(0);
			mood.setReplyAmount(0);
			mood.setTopAmount(0);
			moodDao.saveObject(mood);
		}catch(Exception e){
			log.error(e);
			throw e;
		}
	}
	
}
